package com.pay.utils;

/**
 * Created by chenweiyi on 2018/1/30.
 */
import java.math.BigDecimal;
import java.text.NumberFormat;

public final class MathUtil {

    private static final BigDecimal ONE = new BigDecimal("1.00");
    private static final BigDecimal ZERO = new BigDecimal("0.00");

    private static final int DEFAULT_SCALE = 2;

    /**
     * 保留小数
     * @param obj   数字
     * @param scale 小数的位数
     * @return
     */
    public static BigDecimal roundScale(Object obj,int scale){
        try{
            BigDecimal number = new BigDecimal(String.valueOf(obj)).divide(ONE);
            number = number.setScale(scale,BigDecimal.ROUND_HALF_UP);
            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(scale);
            numberFormat.setMinimumFractionDigits(scale);
            return  new BigDecimal(numberFormat.format(number));
        }catch(Exception e){
            e.printStackTrace();
        }
        return ZERO;
    }

    /**
     * 保留两位小数
     * @param obj
     * @return
     */
    public static BigDecimal roundScale(Object obj){

        BigDecimal number = roundScale(obj,DEFAULT_SCALE);

        return number;
    }

}
